package com.hhc.service.impl;

import com.hhc.dto.CourseDTO;
import com.hhc.entity.CourseInfo;
import com.hhc.entity.UserInfo;
import com.hhc.query.UserQuery;
import com.hhc.repository.CourseInfoRepository;
import com.hhc.repository.CourseRepository;
import com.hhc.repository.StudentCourseSelectionRepository;
import com.hhc.repository.TeacherCourseAssignmentRepository;
import com.hhc.service.CourseService;
import com.hhc.utils.RestResult;
import java.time.LocalDateTime;
import java.util.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hhc.dto.CourseQuery;
import com.hhc.entity.StudentCourseSelection;
import org.springframework.beans.BeanUtils;

/**
 * <p>
 *   课程信息业务逻辑服务实现类
 * </p>
 * @author pc
 */
@Slf4j
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StudentCourseSelectionRepository studentCourseSelectionRepository;

    @Autowired
    private CourseInfoRepository courseInfoRepository;

    @Autowired
    private TeacherCourseAssignmentRepository teacherCourseAssignmentRepository;

    /**
     * 查询用户列表（支持条件搜索和分页）
     */
    @Override
    public RestResult<Object> list(CourseQuery query) {
        try {
            // 创建分页条件
            Pageable pageable = PageRequest.of(query.getCurrent() - 1, query.getSize());

            // 执行条件查询
            Page<CourseInfo> coursePage = courseInfoRepository.findByCondition(
                    query.getCourseName(),  // 用户名模糊查询
                    query.getCourseCode(),     // 邮箱模糊查询
                    query.getCredits(),     // 手机号模糊查询
                    pageable              // 分页参数
            );

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("currentPage", query.getCurrent());
            result.put("pageSize", query.getSize());
            result.put("total", coursePage.getTotalElements());  // 总条数
            result.put("data", coursePage.getContent());         // 当前页数据

            return RestResult.success(result);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return RestResult.failed("查询失败");
        }
    }

    @Override
    @Transactional
    public RestResult addCourse(CourseDTO courseDTO) {
        if (courseInfoRepository.findByCourseCode(courseDTO.getCourseCode()).isPresent()) {
            return RestResult.error("000001", "课程编号已存在");
        }

        CourseInfo courseInfo = new CourseInfo();
        courseInfo.setCourseCode(courseDTO.getCourseCode());
        courseInfo.setCourseName(courseDTO.getCourseName());
        courseInfo.setCredits(courseDTO.getCredits());
        courseInfo.setDescription(courseDTO.getDescription());
        // 默认启用
        courseInfo.setStatus(1);
        // 可以根据实际情况修改
        courseInfo.setCreateBy("system");
        courseInfo.setCreateTime(LocalDateTime.now());
        // 可以根据实际情况修改
        courseInfo.setUpdateBy("system");
        courseInfo.setUpdateTime(LocalDateTime.now());

        courseInfoRepository.save(courseInfo);
        return RestResult.success("调用成功");
    }

    @Override
    @Transactional
    public RestResult updateCourse(CourseDTO courseDTO) {
        Optional<CourseInfo> optionalCourse = courseInfoRepository.findById(courseDTO.getCourseId());
        if (optionalCourse.isEmpty()) {
            return RestResult.error("000001", "课程信息不存在");
        }

        if (courseInfoRepository.findByCourseCode(courseDTO.getCourseCode())
                .filter(c -> !c.getId().equals(courseDTO.getCourseId()))
                .isPresent()) {
            return RestResult.error("000001", "课程编号已存在");
        }

        CourseInfo courseInfo = optionalCourse.get();
        courseInfo.setCourseName(courseDTO.getCourseName());
        courseInfo.setCourseCode(courseDTO.getCourseCode());
        courseInfo.setStatus(courseDTO.getStatus());
        courseInfo.setCredits(courseDTO.getCredits());
        courseInfo.setDescription(courseDTO.getDescription());
        // 可以根据实际情况修改
        courseInfo.setUpdateBy("system");
        courseInfo.setUpdateTime(LocalDateTime.now());

        courseInfoRepository.save(courseInfo);
        return RestResult.success("调用成功");
    }

    @Override
    @Transactional
    public RestResult deleteCourse(Long courseId) {
        Optional<CourseInfo> optionalCourse = courseInfoRepository.findById(courseId);
        if (optionalCourse.isEmpty()) {
            return RestResult.error("000001", "课程信息不存在");
        }

        if (studentCourseSelectionRepository.existsByCourseId(courseId) ||
                teacherCourseAssignmentRepository.existsByCourseId(courseId)) {
            return RestResult.error("000001", "课程已被使用，无法删除");
        }

        courseInfoRepository.deleteById(courseId);
        return RestResult.success("调用成功");
    }

    @Override
    @Transactional
    public RestResult changeCourseStatus(Long courseId, Integer status) {
        Optional<CourseInfo> optionalCourse = courseInfoRepository.findById(courseId);
        if (optionalCourse.isEmpty()) {
            return RestResult.error("000001", "课程信息不存在");
        }

        CourseInfo courseInfo = optionalCourse.get();
        courseInfo.setStatus(status);
        // 可以根据实际情况修改
        courseInfo.setUpdateBy("system");
        courseInfo.setUpdateTime(LocalDateTime.now());

        courseInfoRepository.save(courseInfo);
        return RestResult.success("调用成功");
    }

    @Override
    public RestResult<List<CourseDTO>> getAvailableCourseList(CourseQuery query) {
        Pageable pageable = PageRequest.of(query.getCurrent() - 1, query.getSize());
        org.springframework.data.domain.Page<CourseInfo> courseInfoPage = courseInfoRepository.findByStatus(1, pageable);
        List<CourseDTO> courseDTOList = new ArrayList<>();
        for (CourseInfo courseInfo : courseInfoPage.getContent()) {
            CourseDTO courseDTO = new CourseDTO();
            BeanUtils.copyProperties(courseInfo, courseDTO);
            courseDTOList.add(courseDTO);
        }
        return RestResult.success(courseDTOList);
    }

    @Override
    @Transactional
    public RestResult<String> enrollCourse(Long courseId) {
        // 假设此方法从安全上下文中获取学生ID
        Long studentId = getStudentIdFromContext();
        if (studentId == null) {
            return RestResult.failed("000001", "未获取到学生信息");
        }

        Optional<CourseInfo> courseInfoOptional = courseInfoRepository.findById(courseId);
        if (courseInfoOptional.isPresent() && courseInfoOptional.get().getStatus() == 0) {
            return RestResult.failed("000001", "课程不可选");
        }

        if (studentCourseSelectionRepository.findByStudentIdAndCourseId(studentId, courseId).isPresent()) {
            return RestResult.failed("000001", "课程已选择");
        }

        StudentCourseSelection studentCourseSelection = new StudentCourseSelection();
        studentCourseSelection.setStudentId(studentId);
        studentCourseSelection.setCourseId(courseId);
        studentCourseSelection.setSelectionStatus(1);
        studentCourseSelection.setCreateBy("system");
        studentCourseSelection.setUpdateBy("system");
        studentCourseSelectionRepository.save(studentCourseSelection);

        return RestResult.success("选课成功");
    }

    @Override
    public RestResult<List<CourseDTO>> getEnrolledCourseList(CourseQuery query) {
        // 假设此方法从安全上下文中获取学生ID
        Long studentId = getStudentIdFromContext();
        if (studentId == null) {
            return RestResult.failed("000001", "未获取到学生信息");
        }

        Pageable pageable = PageRequest.of(query.getCurrent() - 1, query.getSize());
        List<StudentCourseSelection> studentCourseSelectionList = studentCourseSelectionRepository.findByStudentId(studentId);
        List<CourseDTO> courseDTOList = new ArrayList<>();

        for (StudentCourseSelection studentCourseSelection : studentCourseSelectionList) {
            CourseInfo courseInfo = courseInfoRepository.findById(studentCourseSelection.getCourseId()).orElse(null);
            if (courseInfo != null) {
                CourseDTO courseDTO = new CourseDTO();
                BeanUtils.copyProperties(courseInfo, courseDTO);
                courseDTOList.add(courseDTO);
            }
        }

        return RestResult.success(courseDTOList);
    }

    @Override
    @Transactional
    public RestResult<String> withdrawCourse(Long courseId) {
        // 假设此方法从安全上下文中获取学生ID
        Long studentId = getStudentIdFromContext();
        if (studentId == null) {
            return RestResult.failed("000001", "未获取到学生信息");
        }

        Optional<StudentCourseSelection> studentCourseSelectionOptional =
                studentCourseSelectionRepository.findByStudentIdAndCourseId(studentId, courseId);

        if (!studentCourseSelectionOptional.isPresent()) {
            return RestResult.failed("000001", "未选该课程");
        }

        StudentCourseSelection studentCourseSelection = studentCourseSelectionOptional.get();
        studentCourseSelection.setSelectionStatus(0);
        studentCourseSelection.setUpdateBy("system");
        studentCourseSelectionRepository.save(studentCourseSelection);

        return RestResult.success("退选成功");
    }

    private Long getStudentIdFromContext() {
        // 实际项目中应从安全上下文中获取当前登录用户信息
        return 1L; // 示例返回值
    }
}
